import { getUserInfo, login } from '@/api/user'

import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },

    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, NewUserInfo) {
      state.userInfo = NewUserInfo
    }
  },
  actions: {
    async login(context, data) {
      const token = await login(data)
      context.commit('setToken', token)
    },
    async getUserInfo(context) {
      const res = await getUserInfo()

      context.commit('setUserInfo', res)
    },
    logout(context) {
      // 清除token
      context.commit('removeToken')
      // 清除用户信息
      context.commit('setUserInfo', {})
    }
  }
}
